<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Recommendation System</title>
    <script>
        // 使用欧几里得距离计算两个用户之间的相似度
        function similarity(user1, user2) {
            let sum = 0;
            for (let i = 0; i < user1.length; i++) {
                if (user1[i] !== -1 && user2[i] !== -1) { // -1 表示未评分
                    sum += Math.pow(user1[i] - user2[i], 2);
                }
            }
            return 1 / (1 + Math.sqrt(sum)); // 返回相似度值
        }

        // 预测用户对某物品的评分
        function predict(ratings, userIndex, itemIndex) {
            let numerator = 0;
            let denominator = 0;
            for (let i = 0; i < ratings.length; i++) {
                if (i !== userIndex && ratings[i][itemIndex] !== -1) {
                    let sim = similarity(ratings[userIndex], ratings[i]);
                    numerator += sim * ratings[i][itemIndex];
                    denominator += sim;
                }
            }
            return denominator === 0 ? 0 : numerator / denominator;
        }

        // 用户-物品评分矩阵, -1 表示未评分
        const ratings = [
            [5, 3, -1, 1],
            [4, -1, -1, 1],
            [1, 1, -1, 5],
            [1, -1, -1, 4],
            [-1, 1, 5, 4],
        ];

        // 在页面加载完成后打印预测结果
        window.onload = function() {
            // 预测用户0（索引为0）对物品2（索引为2）的评分
            console.log(`Predicted rating of user 0 for item 2: ${predict(ratings, 0, 2)}`);
        };
    </script>
</head>
<body>
    <h1>Recommendation System Example</h1>
    <p>Open your browser's console to see the predicted rating.</p>
</body>
</html>